package services

import (
	"TaskAssignmentSystem/internal/admin/dao"
	"TaskAssignmentSystem/pkg/utils"
	"errors"
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

type SystemDictService struct {
}

func (s *SystemDictService) GetUserAgreement() (result string, err error) {
	var systemDictDao dao.Common[dao.SystemDict]
	systemDictDao.CustomWhere = append(systemDictDao.CustomWhere, fmt.Sprintf("dict_code = 'ZXZ_USER_AGREEMENT'"))
	res, err := systemDictDao.First(map[string]interface{}{})
	if err != nil {
		return "", errors.New("用户协议不存在")
	}
	return res.DictValue, nil
}

func (s *SystemDictService) GetDictByCode(code string) (res dao.SystemDict, err error) {
	var systemDictDao dao.Common[dao.SystemDict]
	systemDictDao.CustomWhere = append(systemDictDao.CustomWhere, fmt.Sprintf("dict_code = '%s'", code))
	res, err = systemDictDao.First(map[string]interface{}{})
	if err != nil {
		return res, errors.New("数据不存在")
	}
	return res, nil
}
func (s *SystemDictService) IsMobile(mobile string) bool {
	if data, err := s.GetValueByType("ZXZ_PHONE_CODE"); err != nil {
		return false
	} else {
		phoneCode := []string{}
		for _, code := range data {
			phoneCode = append(phoneCode, code.DictValue)
		}
		result, _ := regexp.MatchString("^("+strings.Join(phoneCode, "|")+")\\d{8}$", mobile)
		if result {
			return true
		} else {
			return false
		}
	}
}

func (s *SystemDictService) GetValueByCode(code string) (result string, err error) {
	var systemDictDao dao.Common[dao.SystemDict]
	systemDictDao.CustomWhere = append(systemDictDao.CustomWhere, fmt.Sprintf("dict_code = '%s'", code))
	res, err := systemDictDao.First(map[string]interface{}{})
	if err != nil {
		return "", errors.New("数据不存在")
	}
	return res.DictValue, nil
}

func (s *SystemDictService) GetValueByType(dtype string) (result []dao.SystemDict, err error) {
	var systemDictDao dao.Common[dao.SystemDict]
	systemDictDao.Query = map[string]interface{}{"dict_type": dtype}
	res, err := systemDictDao.FindAllOrderBy(systemDictDao.Query, "dict_number asc")
	if err != nil {
		return result, errors.New("数据不存在")
	}
	return res, nil
}

func (s *SystemDictService) UpdateValueAndNumber(id, number uint, val string) error {
	var systemDictDao dao.Common[dao.SystemDict]
	set := map[string]interface{}{"dict_number": number}
	if val != "" {
		set["dict_value"] = val
	}
	return systemDictDao.UpdateOne(id, set).Error
}

func (s *SystemDictService) GetUserNumber() (result string, err error) {
	var systemDictDao dao.Common[dao.SystemDict]
	systemDictDao.CustomWhere = append(systemDictDao.CustomWhere, fmt.Sprintf("dict_code = 'ZXZ_USER_NUMBER'"))
	res, err := systemDictDao.First(map[string]interface{}{})
	if err != nil {
		return "", errors.New("数据不存在")
	}
	systemDictDao.Query = map[string]interface{}{"dict_code": "ZXZ_USER_NUMBER"}
	systemDictDao.Update(map[string]interface{}{"dict_value": s.getUserNumberNextValue(res.DictValue)})
	return res.DictValue, nil
}

func (s *SystemDictService) getUserNumberNextValue(oldValue string) (result string) {
	a, _ := strconv.Atoi(oldValue)
	newValue := fmt.Sprintf("%08d", a+1)
	return newValue
}

func (s *SystemDictService) GetTaxRatio() (taxRatio float64, des string, err error) {
	var systemDictDao dao.Common[dao.SystemDict]
	systemDictDao.CustomWhere = append(systemDictDao.CustomWhere, fmt.Sprintf("dict_code = 'ZXZ_TAX_RATIO'"))
	res, err := systemDictDao.First(map[string]interface{}{})
	if err != nil {
		return taxRatio, des, errors.New("数据不存在")
	}
	taxRatio, err = utils.StringToFloat64(res.DictValue)
	if err != nil {
		return taxRatio, des, errors.New("劳务税率数据异常")
	}
	return taxRatio, res.Description, nil
}

func (s *SystemDictService) GetTaxAmount(sysUserId string, totalAmount float64) (taxAmount float64, err error) {
	//获取当月总共收入
	var serve SystemOrderService
	if incomeList, incomeErr := serve.OrderIncomeList(sysUserId); incomeErr != nil {
		return taxAmount, incomeErr
	} else {
		var monthTotalAmount float64 = 0 //当月总收入金额
		var monthTaxAmount float64 = 0   //当月总税金
		for i := 0; i < len(incomeList); i++ {
			systemOrderReviewRecord, _ := serve.OrderReviewRecordInfo(incomeList[i].OrderId)
			if systemOrderReviewRecord.Status == 0 || systemOrderReviewRecord.Status == 1 {
				monthTotalAmount += incomeList[i].TotalAmount
				monthTaxAmount += incomeList[i].TaxAmount
			}
		}
		nowMonthTotalAmount := monthTotalAmount + totalAmount
		tax := utils.IncomeAfterTax(nowMonthTotalAmount)
		//获取当月总扣税金额
		return utils.RoundHalfUpValue(nowMonthTotalAmount-tax-monthTaxAmount, utils.DigitNumberAfterDot), nil
	}
}

func (s *SystemDictService) GetNextTeamNumber() (string, error) {
	var systemDictDao dao.Common[dao.SystemDict]
	systemDictDao.CustomWhere = append(systemDictDao.CustomWhere, fmt.Sprintf("dict_code = 'ZXZ_TEAM_NUMBER'"))
	res, err := systemDictDao.First(map[string]interface{}{})
	if err != nil {
		return "", errors.New("服务器连接异常")
	}
	var teamService TeamService
	var next, old string
	old = res.DictValue
	for true {
		//根据规则计算下一个团队编号
		next = s.getTeamNumberNextValue(old)
		//team表中查询是否已存在
		exist, err := teamService.VerifyTeamNumber(next)
		if err != nil {
			return "", errors.New("服务器连接异常")
		}
		if exist {
			//team表中已存在，继续下一个
			old = next
		} else {
			//不存在，则使用
			break
		}
	}
	systemDictDao.Query = map[string]interface{}{"dict_code": "ZXZ_TEAM_NUMBER"}
	systemDictDao.Update(map[string]interface{}{"dict_value": next})
	return next, nil
}

func (s *SystemDictService) getTeamNumberNextValue(oldValue string) string {
	//团队编号为三位数
	//a1a a2a ... a9a
	//a1b a2b ... a9b
	//......
	//z1z z2z ... z9z
	if len(oldValue) != 3 || utils.StringIsEmpty(oldValue) || strings.EqualFold(oldValue, "z9z") {
		oldValue = "a1a"
	}

	arr := strings.Split(oldValue, "")
	one, two, three := arr[0], arr[1], arr[2]
	//中间数字小于9，首尾字母不变，数字+1
	if !strings.EqualFold(two, "9") {
		a, _ := strconv.Atoi(arr[1])
		two = utils.IntToString(a + 1)
		return fmt.Sprintf("%s%s%s", one, two, three)
	}
	//字母表
	letters := "abcdefghijklmnopqrstuvwxyz"
	lettersArr := strings.Split(letters, "")
	lettersIndex := make(map[string]int)
	for i, v := range lettersArr {
		lettersIndex[v] = i
	}
	//数字为9，进一位，数字变为1，尾字母顺序下一位
	two = "1"
	//尾字母不为 z，尾字母顺序下一位
	if !strings.EqualFold(three, "z") {
		i := lettersIndex[three]
		three = lettersArr[i+1]
		return fmt.Sprintf("%s%s%s", one, two, three)
	}
	//尾字母为 z，首字母顺序下一位
	three = "a"
	i := lettersIndex[one]
	one = lettersArr[i+1]
	return fmt.Sprintf("%s%s%s", one, two, three)
}

func (s *SystemDictService) QuerySystemDict(dictCode string) (*dao.SystemDict, error) {
	var commonServe CommonService[dao.SystemDict]

	if utils.StringIsNotEmpty(dictCode) {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("dict_code = '%v'", dictCode))
	}
	if res, err := commonServe.First(); err != nil {
		return nil, err
	} else {
		return &res, nil
	}
}
